{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "import keras\n",
    "import numpy as np"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "word_dim = 10\n",
    "hidden_dim = 1\n",
    "c = np.zeros(word_dim)\n",
    "E = np.random.uniform(-np.sqrt(1./word_dim), np.sqrt(1./word_dim), (hidden_dim, word_dim))\n",
    "\n",
    "def GRU_forward(x_t, h_t_prev):\n",
    "    # 在simple RNN中前馈计算使用的是\n",
    "    # h_t = np.tanh(U.dot(x_t) + W.dot(h_t_prev))\n",
    "    \n",
    "    # 获取\n",
    "    x_t_ = E[:,x_t]\n",
    "       \n",
    "    # GRU\n",
    "    z_t = sigmoid(U[0].dot(x_t_) + W[0].dot(h_t_prev) + b[0]) # update gate\n",
    "    r_t = sigmoid(U[1].dot(x_t_) + W[1].dot(h_t_prev) + b[1]) # reset gate\n",
    "    c_t = np.tanh(U[2].dot(x_t_) + W[2].dot(h_t_prev * r_t) + b[2])\n",
    "    h_t = (1 - z_t) * c_t + z_t * h_t_prev\n",
    "       \n",
    "    # 最后输出概率\n",
    "    x_t = softmax(V.dot(h_t) + c)[0]\n",
    " \n",
    "    return [x_t, s_t1]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def GRU_gradient(y_pred, y):\n",
    "    # 向后传播\n",
    "    loss = categorical_crossentropy(y_pred, y)\n",
    "\n",
    "    # 计算权重参数梯度\n",
    "    dE = keras.grad(loss, E)\n",
    "    dU = keras.grad(loss, U)\n",
    "    dW = keras.grad(loss, W)\n",
    "    db = keras.grad(loss, b)\n",
    "    dV = keras.grad(loss, V)\n",
    "    dc = keras.grad(loss, c)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
